//
//  StatusListViewModel.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/17.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage
class StatusListViewModel: NSObject {
    
    
    //加载微博首页数据
    class func loadData(since_id since_id: Int64, max_id: Int64, finished: (array: [Status]?) -> ()) {
        
        //实例化AFN
        //        let AF = AFHTTPSessionManager()
        
        
        let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("您还没有登录")
            return
        }
        
        var parameters = ["access_token": token]
        //如果制定此参数，返回比since_id大的微博
        if since_id > 0 {
            //添加since_id的对应键值
            parameters["since_id"] = "\(since_id)"
        }
        //如果制定此参数，返回小于或等于max_id的微博
        if max_id > 0 {
            parameters["max_id"] = "\(max_id)"
        }
        
        //   AF.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
        //   guard let dict = result as? [String: AnyObject] else {
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                finished(array: nil)
                return
            }
            
            if let array = result!["statuses"] as? [[String: AnyObject]] {
                var list = [Status]()
                //便利数组
                for item in array {
                    //字典转模型
                    let s = Status(dict: item)
                    //添加微博对象
                    list.append(s)
                }
                //完成回调
//                finished(array: list)
                StatusListViewModel.cacheStatusImage(list, finished: finished)
            }
        }
    }
    
    private class func cacheStatusImage(array: [Status],finished: (array: [Status]?) -> ()){
        //缓存单张图片
        if array.count == 0 {
            //完成回调
            finished(array: nil)
            return
        }
        
        //
        let group = dispatch_group_create()
        
        for s in array {
            if let imageurls = s.pictureURLs{
                if imageurls.count != 1 {
                    continue
                }
                //一定是单张图片
                for url in imageurls{
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        print("单张图片下载完成")
                        //异步任务离开群组
                        dispatch_group_leave(group)
                    })
                }
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("所有的图片异步下载完成")
            //在主线程完成回调
            finished(array: array)
        }
        
    }
    
    
    
}
